<!DOCTYPE html>
<html lang="en-US">
  <head>
    <link href="/assets/index.css" rel="stylesheet" type="text/css" />
    <script crossorigin="anonymous" src="/test-harness.js"></script>
    <script crossorigin="anonymous" src="/test-page-object.js"></script>
    <script crossorigin="anonymous" src="/__dist__/webchat-es5.js"></script>
  </head>
  <body>
    <main id="webchat"></main>
    <script>
      run(
        async function () {
          const store = testHelpers.createStore({}, ({ dispatch }) => next => action => {
            if (action.type === 'DIRECT_LINE/INCOMING_ACTIVITY' && action.payload.activity) {
              if (action.payload.activity.from.role === 'bot' && action.payload.activity.type === 'message') {
                // We are dispatching an invalid action that would cause Web Chat core to fail, producing a fatal error.
                dispatch({
                  type: 'DIRECT_LINE/POST_ACTIVITY',
                  payload: {}
                });
              } else if (action.payload.activity.from.role === 'user') {
                // Do not send echo back because sometimes, we will receive it, and sometimes don't, due to race conditions in sagas.
                // Better not send all of them to make our test more reliable.
                return;
              }
            }

            return next(action);
          });

          WebChat.renderWebChat(
            {
              directLine: WebChat.createDirectLine({ token: await testHelpers.token.fetchDirectLineToken() }),
              store,
              styleOptions: { spinnerAnimationBackgroundImage: 'url(/assets/staticspinner.png)' }
            },
            document.getElementById('webchat')
          );

          await pageConditions.uiConnected();
          await pageConditions.allOutgoingActivitiesSent();

          // WHEN: Sending an message.
          await pageObjects.sendMessageViaSendBox('error', { waitForSend: false });

          // THEN: The INCOMING_ACTIVITY from the bot should trigger the saga error.
          await pageConditions.minNumActivitiesShown(2);
          await pageConditions.actionDispatched('WEB_CHAT/SAGA_ERROR');

          // THEN: The error status should be displayed.
          await pageConditions.connectivityStatusShown(/render error/iu);

          // THEN: SAGA_ERROR will cancel all sagas, thus, `activity.channelState['webchat:send-status']` will become `"send failed"`.
          //       As a result, the timestamp on the screenshot should become "Send failed, retry."
          await host.snapshot();
        },
        { ignoreErrors: true }
      );
    </script>
  </body>
</html>
